package com.z.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.z.common.base.ResponseCode;
import com.z.common.base.Results;
import com.z.admin.dao.CarouselMapper;
import com.z.admin.entity.Carousel;
import com.z.admin.service.ICarouselService;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author z
 * @since 2022-03-13
 */
@Service
public class CarouselServiceImpl extends ServiceImpl<CarouselMapper, Carousel> implements ICarouselService {
    @Resource
    private CarouselMapper carouselMapper;
    @Override
    public Results<List<Carousel>> findPageByMap(Map<String, Object> map, Integer offset, Integer limit) {
        StringBuffer where = new StringBuffer("");
        if(map != null && map.size() > 0){
            where.append("where ");
            for(Map.Entry<String, Object> entry : map.entrySet()){
                String[] strArr = entry.getKey().split("_");
                where.append(strArr[0]+" ");
                if(strArr[1].equals("like")){
                    where.append("like '%" +entry.getValue()+"%' and ");
                }else{
                    where.append("= '" +entry.getValue()+"' and ");
                }
            }
            where.delete(where.length()-4, where.length());
        }
        return Results.success(carouselMapper.conutByMap(where.toString()), carouselMapper.findPageByWhereSql(where.toString(), offset, limit));
    }

    @Override
    public Results delAll(String ids) {
        try{
            File file = null;
            for(String id : ids.split(",")) {
                String url = carouselMapper.selectById(id).getUrl();
                if(!StringUtils.isEmpty(url)){
                    file = new File(url);
                    if (file != null && file.exists()) {
                        file.delete();
                    }
                }
                carouselMapper.deleteById(id);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Results.failure(ResponseCode.error.getCode(), e.getMessage());
        }
        return Results.success();
    }
}
